<template>
  <div class="price-prediction">
    <h1>车辆价格预测</h1>

    <!-- 参数配置区域 -->
    <section class="params-section">
      <div class="param-group">
        <label for="months-slider">预测月份</label>
        <div class="slider-container">
          <input
            type="range"
            id="months-slider"
            v-model.number="months"
            min="1"
            max="12"
            step="1"
          />
          <span class="slider-value">{{ months }} 个月</span>
        </div>
      </div>

      <div class="param-group">
        <label>考虑季节性影响</label>
        <ToggleSwitch v-model="seasonal" />
      </div>

      <div class="param-row">
        <div class="param-group">
          <CommonSelector
            label="能源类型"
            v-model="energy"
            :options="energyOptions"
            placeholder="请选择能源类型"
          />
        </div>
        <div class="param-group">
          <CommonSelector
            label="车辆级别"
            v-model="level"
            :options="levelOptions"
            placeholder="请选择车辆级别"
          />
        </div>
      </div>
    </section>

    <!-- 预测按钮 -->
    <section class="action-section">
      <button class="predict-btn" @click="predictPrice">预测价格</button>
    </section>

    <!-- 预测结果展示 -->
    <section v-if="showResults" class="results-section">
      <h2>价格预测结果（模拟数据）</h2>
      <div class="chart-info">
        <p class="date-range">预测时间范围: {{ startDate }} 至 {{ endDate }}</p>
      </div>
      <div class="chart-container">
        <div class="line-chart" ref="chartContainer">
          <svg class="chart-svg" ref="chartSvg" viewBox="0 0 800 460">
            <!-- 坐标轴 -->
            <g class="axes">
              <!-- Y轴 -->
              <line x1="80" y1="50" x2="80" y2="350" stroke="#666" stroke-width="2"/>
              <!-- X轴 -->
              <line x1="80" y1="350" x2="750" y2="350" stroke="#666" stroke-width="2"/>
              
              <!-- Y轴刻度和标签 -->
              <g class="y-axis-labels">
                <text x="70" y="55" text-anchor="end" font-size="12" fill="#666">100万</text>
                <text x="70" y="105" text-anchor="end" font-size="12" fill="#666">80万</text>
                <text x="70" y="155" text-anchor="end" font-size="12" fill="#666">60万</text>
                <text x="70" y="205" text-anchor="end" font-size="12" fill="#666">40万</text>
                <text x="70" y="255" text-anchor="end" font-size="12" fill="#666">20万</text>
                <text x="70" y="305" text-anchor="end" font-size="12" fill="#666">0万</text>
              </g>
              
              <!-- X轴标签 -->
              <g class="x-axis-labels">
                <text 
                  v-for="(label, i) in labelPositions" :key="i"
                  :x="label.x"
                  :y="label.y"
                  :transform="label.transform"
                  text-anchor="middle"
                  :font-size="label.fontSize"
                  fill="#666">
                  {{ label.date }}
                </text>
              </g>
            </g>
            
            <!-- 折线 -->
            <polyline
              v-if="mockPrices.length > 1"
              class="price-line"
              :points="linePoints"
              fill="none"
              stroke="#4CAF50"
              stroke-width="3"
              stroke-linecap="round"
              stroke-linejoin="round"
            />
            
            <!-- 数据点 -->
            <g class="data-points">
              <circle
                v-for="(point, i) in dataPointPositions"
                :key="i"
                :cx="point.x"
                :cy="point.cy"
                r="6"
                fill="#4CAF50"
                stroke="white"
                stroke-width="2"
                class="data-point"
                @mouseenter="showTooltip(i)"
                @mouseleave="hideTooltip"
              />
            </g>
          </svg>
          
          <!-- 悬停提示框 -->
          <div v-if="tooltip.show" class="tooltip" :style="tooltipStyle">
            <p class="tooltip-date">{{ tooltip.date }}</p>
            <p class="tooltip-price">{{ tooltip.price }}万元</p>
          </div>
        </div>
      </div>
      
      <!-- 图例 -->
      <div class="legend">
        <div class="legend-item">
          <span class="legend-color"></span>
          <span>预测价格趋势</span>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import ToggleSwitch from '@/components/ToggleSwitch.vue';
import CommonSelector from '@/components/CommonSelector.vue';

export default {
  name: 'PricePrediction',
  components: {
    ToggleSwitch,
    CommonSelector
  },
  data() {
    return {
      months: 6,
      seasonal: false,
      energy: '',
      level: '',
      showResults: false,
      mockPrices: [],
      chartDates: [],
      tooltip: {
        show: false,
        date: '',
        price: 0,
        x: 0,
        y: 0
      }
    };
  },
  computed: {
    energyOptions() {
      return [
        '汽油', '48V 轻混系统', '油电混动', '纯电动',
        '汽油电驱', '增程式电动', '插电混动', '柴油'
      ];
    },
    levelOptions() {
      return [
        '中大型 MPV', '中大型 SUV', '中型 SUV', '中型皮卡',
        '全尺寸皮卡', '大型 SUV', '紧凑型 SUV', '紧凑型车',
        '微卡', '微型车', '微面', '房车', '轻客', '跑车'
      ];
    },
    startDate() {
      const today = new Date();
      return this.formatDate(today);
    },
    endDate() {
      const today = new Date();
      const endDate = new Date(today);
      
      // 添加指定月数，保持相同的日期
      endDate.setMonth(today.getMonth() + this.months);
      
      // 处理月份边界情况（如从1月31日加1个月）
      if (endDate.getDate() !== today.getDate()) {
        endDate.setDate(0); // 设置为上个月的最后一天
      }
      
      return this.formatDate(endDate);
    },
    linePoints() {
      if (this.mockPrices.length <= 1) return '';
      return this.positions.slice(0, this.mockPrices.length).map((p, i) => `${p.x},${350 - this.mockPrices[i] * 3}`).join(' ');
    },
    tooltipStyle() {
      return {
        left: this.tooltip.x + 'px',
        top: this.tooltip.y + 'px'
      };
    },
    shouldRotate() {
      return this.chartDates.length > 6;
    },
    positions() {
      const len = this.chartDates.length;
      if (len === 0) return [];
      return Array.from({length: len}, (_, i) => {
        const x = len === 1 ? 360 : (120 + i * (600 / (len - 1)));
        return { x };
      });
    },
    labelPositions() {
      const rotate = this.shouldRotate;
      const pos = this.positions;
      const labelY = rotate ? 368 : 370;
      const rotY = rotate ? 385 : 370;
      const fontSize = rotate ? 10 : 12;
      return pos.map((p, i) => ({
        x: p.x,
        y: labelY,
        transform: rotate ? `rotate(-45, ${p.x}, ${rotY})` : '',
        fontSize,
        date: this.chartDates[i]
      }));
    },
    dataPointPositions() {
      return this.positions.map((p, i) => ({
        x: p.x,
        cy: 350 - (this.mockPrices[i] || 0) * 3
      }));
    }
  },
  methods: {
    predictPrice() {
      // 生成日期数据
      this.generateChartDates();
      
      // 模拟生成预测数据（价格范围20-100万），生成months+1个数据点
      this.mockPrices = Array.from({ length: this.months + 1 }, () =>
        20 + Math.random() * 80
      );
      this.showResults = true;
      console.log('预测参数：', {
        months: this.months,
        seasonal: this.seasonal,
        energy: this.energy,
        level: this.level,
        startDate: this.startDate,
        endDate: this.endDate,
        chartDates: this.chartDates,
        mockPrices: this.mockPrices
      });
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}年${month}月${day}日`;
    },
    generateChartDates() {
      const dates = [];
      const today = new Date();
      
      // 生成每个月的日期标签，包括起始月份
      for (let i = 0; i <= this.months; i++) {
        const targetDate = new Date(today);
        targetDate.setMonth(today.getMonth() + i);
        
        // 格式化日期显示，如：2025年11月
        const year = targetDate.getFullYear();
        const month = String(targetDate.getMonth() + 1).padStart(2, '0');
        dates.push(`${year}年${month}月`);
      }
      
      this.chartDates = dates;
    },
    showTooltip(index) {
      const chartRect = this.$refs.chartContainer.getBoundingClientRect();
      const svg = this.$refs.chartSvg;
      const point = svg.createSVGPoint();
      const dataPoint = this.dataPointPositions[index];
      point.x = dataPoint.x;
      point.y = dataPoint.cy;
      const svgPoint = point.matrixTransform(svg.getScreenCTM());
      let tooltipX = svgPoint.x - chartRect.left + 10;
      let tooltipY = svgPoint.y - chartRect.top - 20;
      // 防止超出右侧
      const approxTooltipWidth = 140;
      if (tooltipX + approxTooltipWidth > chartRect.width) {
        tooltipX = svgPoint.x - chartRect.left - approxTooltipWidth - 10;
      }
      this.tooltip = {
        show: true,
        date: this.chartDates[index],
        price: Math.round(this.mockPrices[index] * 100) / 100,
        x: tooltipX,
        y: tooltipY
      };
    },
    hideTooltip() {
      this.tooltip.show = false;
    }
  }
};
</script>

<style scoped>
.price-prediction {
  max-width: 1000px;
  margin: 0 auto;
  padding: 2rem;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.price-prediction h1 {
  text-align: center;
  color: #4CAF50;
  font-size: 2.5rem;
  margin-bottom: 3rem;
  font-weight: 700;
}

.price-prediction h2 {
  color: #333;
  margin-bottom: 1.5rem;
}

.params-section,
.results-section {
  background: white;
  padding: 2.5rem;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(76, 175, 80, 0.1);
  margin-bottom: 2rem;
}

.param-group {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  margin-bottom: 1.5rem;
}

.param-group label {
  font-weight: 600;
  color: #333;
  font-size: 1rem;
}

.param-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
}

.slider-container {
  display: flex;
  align-items: center;
  gap: 1rem;
}

#months-slider {
  flex: 1;
  height: 8px;
  border-radius: 4px;
  background: #e0e0e0;
  outline: none;
  -webkit-appearance: none;
  appearance: none;
}

#months-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #4CAF50;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

#months-slider::-moz-range-thumb {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #4CAF50;
  cursor: pointer;
  border: none;
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

.slider-value {
  font-size: 1.2rem;
  font-weight: 600;
  color: #4CAF50;
  min-width: 60px;
  text-align: center;
}

.action-section {
  text-align: center;
  margin: 3rem 0;
}

.predict-btn {
  background: linear-gradient(135deg, #4CAF50, #45a049);
  color: white;
  border: none;
  padding: 1.2rem 3rem;
  font-size: 1.2rem;
  font-weight: 600;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);
}

.predict-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(76, 175, 80, 0.4);
  background: linear-gradient(135deg, #45a049, #4CAF50);
}

.chart-container {
  background: #f8f9fa;
  padding: 2rem;
  border-radius: 8px;
  overflow: hidden;
}

.chart-info {
  margin-bottom: 1rem;
  text-align: center;
}

.date-range {
  color: #666;
  font-size: 1rem;
  font-weight: 500;
}

.line-chart {
  position: relative;
  height: 460px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.chart-svg {
  width: 100%;
  height: 100%;
}

.price-line {
  filter: drop-shadow(0 2px 4px rgba(76, 175, 80, 0.3));
  animation: drawLine 1s ease-in-out;
}

@keyframes drawLine {
  from {
    stroke-dasharray: 1000;
    stroke-dashoffset: 1000;
  }
  to {
    stroke-dasharray: 1000;
    stroke-dashoffset: 0;
  }
}

.data-point {
  cursor: pointer;
  transition: all 0.3s ease;
}

.data-point:hover {
  filter: drop-shadow(0 0 10px rgba(76, 175, 80, 0.5));
}

.tooltip {
  position: absolute;
  background: rgba(0, 0, 0, 0.87);
  color: white;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 12px;
  white-space: nowrap;
  pointer-events: none;
  z-index: 1000;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.tooltip p {
  margin: 0;
}

.tooltip-date {
  font-size: 11px;
  opacity: 0.9;
  margin-bottom: 2px;
}

.legend {
  display: flex;
  justify-content: center;
  margin-top: 1.5rem;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem 1.5rem;
  background: white;
  border-radius: 25px;
  box-shadow: 0 4px 15px rgba(76, 175, 80, 0.12);
  color: #4CAF50;
  font-weight: 500;
}

.legend-color {
  width: 20px;
  height: 3px;
  background: linear-gradient(90deg, #4CAF50, #45a049);
  border-radius: 2px;
}

@media (max-width: 768px) {
  .price-prediction {
    padding: 1.5rem 1rem;
  }

  .price-prediction h1 {
    font-size: 2rem;
    margin-bottom: 2rem;
  }

  .params-section,
  .results-section {
    padding: 2rem 1.5rem;
  }

  .param-row {
    grid-template-columns: 1fr;
    gap: 1.5rem;
  }

  .slider-container {
    gap: 0.75rem;
  }

  .predict-btn {
    padding: 1rem 2.5rem;
    font-size: 1.1rem;
  }

  .chart-container {
    padding: 1.5rem;
  }

  .line-chart {
    height: 400px;
  }
}
</style>